import { useCallback, useEffect } from 'react';
import { ErrorBoundary } from 'react-error-boundary';

import PageError from '@/pages/sys/error/PageError';
import { useUserToken, useUserInfo, useUserActions, useAnonymousSignIn } from '@/store/userStore';

import { useParams, useRouter } from '../hooks';

import Cookies from 'js-cookie';
import { USER_LIST } from '@/_mock/assets';
import { jwtDecode } from 'jwt-decode';

import useInitialize from '@/hooks/event/use-initialize';
import { log } from 'console';
import { StorageEnum } from '@/types/enum';
import orchestrationService from '@/api/services/orchestrationService';
const { VITE_TOKEN: VITETOKEN } = import.meta.env;

type Props = {
  children: React.ReactNode;
};
export default function ShareAuthGuard({ children }: Props) {
  const router = useRouter();
  const { accessToken } = useUserToken();
  const { username } = useUserInfo();
  const { share_code, app_id, share_id } = useParams() as { share_code: string, app_id: string, share_id: string };
  const { setUserToken, setUserInfo } = useUserActions();
  const { replace } = useRouter();
  const signIn = useAnonymousSignIn();
  const check = useCallback(async () => {
    if (!window.location.pathname.startsWith('/sharelink/')) {
      return
    }
    const res = await signIn(share_code);
    console.log(res);
    if (!res) {
      window.location.href = '/share-link-error';
      return;
    }

    if (!accessToken || !username || res.token || res?.[VITETOKEN] != accessToken) {
      let token = res?.[VITETOKEN];
      const fakerUser = USER_LIST[0];
      try {
        const decodedToken = jwtDecode(token);
        localStorage.setItem(StorageEnum.protocolName, decodedToken?.protocolName || "");
        console.log('Decoded Token:', decodedToken);
        console.log('token ', token, VITETOKEN);
        if (decodedToken?.userName) {
          const mergeUser = {
            ...fakerUser,
            username: decodedToken.userName ? decodedToken.userName : 'user',
            ...(decodedToken?.roles && {
              role: (() => {
                if (!Array.isArray(decodedToken.roles)) {
                  return decodedToken.roles;
                } else {
                  if (decodedToken.roles.length === 1) {
                    return decodedToken.roles[0];
                  } else {
                    const role = {
                      list: decodedToken.roles,
                      name: decodedToken.roles.map((item) => item.name).join('/'),
                      code: decodedToken.roles.map((item) => item.code),
                    };
                    return role;
                  }
                }
              })(),
            }),
          };

          setUserInfo(mergeUser);
          setUserToken({ accessToken: token, refreshToken: token });
          // replace('/');


          replace(`/apps/chat?appId=${app_id}&shareId=${share_id}`);
        } else {
          window.location.href = '/share-link-error';
        }
      } catch (err) {
        window.location.href = '/share-link-error';
      }
    } else {
      window.location.href = '/';
    }
  }, [router, accessToken]);

  useEffect(() => {
    check();
  }, [check]);

  return <ErrorBoundary FallbackComponent={PageError}>{children}</ErrorBoundary>;
}
